const router = require('express').Router()
const sql = require('./../sql')
const Cart = require('./../sql/models/Cart')
const Address = require('./../sql/models/Address')
const Order = require('./../sql/models/Order')
const Product = require('./../sql/models/Product')
const utils = require('./../utils')
router.post('/updateOrderAddress', (req, res, next) => {
  console.log(111)
  const { userid, createTime, userName, telNumber, 
    provinceName, cityName, countyName,detailInfo} = req.body
    console.log( req.body)
  sql.update(Order, { userid, createTime }, { $set: {userName, telNumber, 
    provinceName, cityName, countyName,detailInfo} }, 1).then(() => {
      res.status(200).send({
        code: '200',
        message: '修改订单的地址'
      })
    })

})
router.get('/confirmOrder', (req, res, next) => {
  const { userid, createTime } = req.query
  sql.find(Order, { userid, createTime }, { _id: 0, __v: 0}).then(data => {
    // 查询该订单有没有地址信息
    var flag = false
    let obj = {}
    if (data[0].telNumber === '') {
      flag = false
    } else {
      flag = true
      obj = {
        userName: data[0].userName,
        telNumber: data[0].telNumber,
        provinceName: data[0].provinceName,
        cityName: data[0].cityName,
        countyName: data[0].countyName,
        detailInfo: data[0].detailInfo,
      }
    }
    const sendObj = {
      code: '200',
      message: '获取确认订单的信息',
      flag,
      data
    }
    flag && (sendObj.address = obj)
    res.status(200).send(sendObj)
  })
})

router.post('/addOrder', (req, res, next) => {
  const insertData = req.body
  // 以购物车选中的商品为基准值，添加其他的字段
  sql.find(Cart, { userid: insertData.userid, flag: true },
    { _id: 0,
      proid: 1,
      num: 1
    }).then(data => {
      // data  [{proid: '', num: }, {proid: '', num}, { proid: ''}]
      // 遍历数据查询产品的信息
      const arr = []
      data.forEach(item => {
        arr.push(sql.find(Product, { proid: item.proid}, { 
          _id: 0,proid: 1, proname: 1, discount: 1, originprice: 1, img1: 1
        }))
      })
      Promise.all(arr).then(result => {
        // result [[{}], [{}]]
        const dataarr = []
        result.forEach(item => {
          dataarr.push(item[0])
        })
        // dataarr [{proid: '', proname: '', discount: '', originprice: '', img1: ''}, {}]
        // 判断用户有没有默认地址，有的话就把订单的地址设置为默认地址
        sql.find(Address, { userid: insertData.userid, isDefault: true }).then(data1 => {
          let obj = {}
          if (data1.length === 0) {
            // 没有默认地址  ---- 用户还没有添加过地址
            obj = { // 此次确认订单页面的所有商品的公共 地址数据
              userName: '',
              telNumber: '',
              provinceName: '',
              cityName: '',
              countyName: '',
              detailInfo: '',
            }
          } else {
            obj = { // 此次确认订单页面的所有商品的公共 地址数据
              userName: data1[0].userName,
              telNumber: data1[0].telNumber,
              provinceName: data1[0].provinceName,
              cityName: data1[0].cityName,
              countyName: data1[0].countyName,
              detailInfo: data1[0].detailInfo,
            }
          }
          const resultarr = []
          const createTime = new Date().getTime() + ''
          // 遍历dataarr 添加其他的数据
          dataarr.forEach((item, index) => {
            resultarr.push({
              userName: obj.userName,
              telNumber: obj.telNumber,
              provinceName: obj.provinceName,
              cityName: obj.cityName,
              countyName: obj.countyName,
              detailInfo: obj.detailInfo,
              orderid: 'order_' + utils.getUuid(),
              userid: insertData.userid,
              status: 0,
              proname: item.proname,
              proid: item.proid,
              originprice: item.originprice,
              img1: item.img1,
              discount: item.discount,
              num: data[index].num,
              createTime
            })
          })

          // 插入数据
          sql.insert(Order, resultarr).then(() => {

            res.status(200).send({
              code: '200',
              message: '添加订单',
              createTime
            })
          })
          
        })
        
      })
      
    })
})
router.get('/deleteCartItem', (req, res, next) => {
  const { userid } = req.query
  sql.delete(Cart, { userid, flag: true }, 1).then(() => {
    res.status(200).send({
      code:'200',
      message: '支付时删除购物车选中的数据'
    })
  })
})

module.exports = router